﻿using DDS.IoT.Com;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DDS.IoT.Mqtt
{
    public class MqttClientCom : ComBase
    {
        public override string Type => "mqttClientCom";

        public override string Name => "Mqtt客户端";
        private MqttClientService mqttClientService;

        public override bool Init(int port, int baudRate = 9600, string extendData = null)
        {
            mqttClientService = new MqttClientService();
            mqttClientService.PushId = this.Id;
            this.Port = port;
            mqttClientService.MqttClientStart(extendData,this.OnPushData);
            Console.WriteLine("初始化MqttClientCom驱动程序成功！");
            return true;
        }
        public override event PushData OnPushData;

        public override bool Open()
        {
            var b = false;
            try
            {
                mqttClientService.Open();
                b = true;
                IsOpen = true;
            }
            catch (Exception ex)
            {

                string msg = string.Format("MqttClientCom串口打开失败：{0} ", ex.Message);
                Console.WriteLine(msg);
            }
            return b;
        }

        public override bool Close()
        {
            mqttClientService.Close();
            mqttClientService = null;
            IsOpen = false;
            OnPushData = null;
            return true;
        }

        public override string Command(string name, string data)
        {
            var outData = string.Empty;

            var dataObj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(data);
            switch (name)
            {
                case "Publish":
                    string topic = dataObj.topic;
                    string payload = dataObj.data;
                    int? level = dataObj.level;
                    bool? retain = dataObj.retain;
                    if (!level.HasValue)
                    {
                        level = 1;
                    }
                    if (!retain.HasValue)
                    {
                        retain = false;
                    }
                    outData =mqttClientService.Publish(topic, payload, level.Value, retain.Value).ToString();
                    break;
                case "Subscribe":
                    topic = dataObj.topic;
                    level = dataObj.level;
                    if (!level.HasValue)
                    {
                        level = 0;
                    }
                    outData = mqttClientService.Subscribe(topic, level.Value).ToString();
                    break;
            }
            return outData;
        }
    }
}
